package com.hcb.micro.controller;

import java.text.DateFormat;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.hcb.micro.controller.base.BaseControllers;
import com.hcb.micro.dto.AccountPlatform;
import com.hcb.micro.dto.Mall;
import com.hcb.micro.dto.Manager;
import com.hcb.micro.dto.Order;
import com.hcb.micro.dto.OrderLogistics;
import com.hcb.micro.dto.OrderProduct;
import com.hcb.micro.dto.OrderProductRefund;
import com.hcb.micro.dto.Product;
import com.hcb.micro.dto.ProductColor;
import com.hcb.micro.dto.ProductProcessingMethods;
import com.hcb.micro.dto.ProductSeller;
import com.hcb.micro.dto.ProductSize;
import com.hcb.micro.dto.ProductStyle;
import com.hcb.micro.service.IAccountPlatformService;
import com.hcb.micro.service.IMallService;
import com.hcb.micro.service.IOrderLogisticsService;
import com.hcb.micro.service.IOrderProductRefundService;
import com.hcb.micro.service.IOrderProductService;
import com.hcb.micro.service.IOrderReceiveAddressService;
import com.hcb.micro.service.IOrderService;
import com.hcb.micro.service.IProductColorService;
import com.hcb.micro.service.IProductProcessingMethodsService;
import com.hcb.micro.service.IProductSellerService;
import com.hcb.micro.service.IProductService;
import com.hcb.micro.service.IProductSizeService;
import com.hcb.micro.service.IProductStyleService;
import com.hcb.micro.service.IQqbsAccountService;
import com.hcb.micro.util.CommonConstant;
import com.hcb.micro.util.KdCompanyEnum;
import com.hcb.micro.dto.QqbsAccount;

import net.sf.json.JSONObject;

@Controller
@RequestMapping("order")
public class OrderController extends BaseControllers{

	@Autowired
	IMallService mallService;
	
	@Autowired
	IOrderService orderService;
	
	@Autowired
	IOrderProductService orderProductService;
	
	@Autowired
	IQqbsAccountService qqbsAccountService;
	
	@Autowired
	IOrderReceiveAddressService orderReceiveAddressService;
	
	@Autowired
	IProductService productService;
	
	@Autowired
	IOrderLogisticsService orderLogisticsService;
	
	@Autowired
	IProductSellerService productSellerService;
	
	@Autowired
	IProductColorService productColorService;
	
	@Autowired
	IProductProcessingMethodsService productProcessingMethodsService;
	
	@Autowired
	IProductStyleService productStyleService;
	
	@Autowired
	IProductSizeService productSizeService;
	
	@Autowired
	IAccountPlatformService accountPlatformService;
	
	@Autowired
	IOrderProductRefundService orderProductRefundService;
	
	@RequestMapping(value = "list", method = RequestMethod.POST)
	@ResponseBody
	public String list() {
		JSONObject json = new JSONObject();
		if (sign == 1) {
			json.put("result", "1");
			json.put("description", "请检查参数格式是否正确或者参数是否完整");
			return buildReqJsonInteger(1, json);
		}
		// 登录认证失败
		if (sign == 2) {
			json.put("result", "2");
			json.put("description", "账号未登录");
			return buildReqJsonInteger(2, json);
		}
		
		HttpSession session = request.getSession();
		Manager manager = (Manager) session.getAttribute("MANAGER");
        if(manager == null){
        	json.put("result", "1");
			json.put("description", "账号未登陆");
			return buildReqJsonObject(json);
        }
		
		JSONObject bodyInfo = JSONObject.fromObject(bodyString);
		
		Map<String,Object> para = new HashMap<>();
		if (bodyInfo.get("orderId") != null && !"".equals(bodyInfo.get("orderId"))) {
			para.put("orderId", bodyInfo.getString("orderId"));
		}
		if(bodyInfo.get("accountId") != null && !"".equals(bodyInfo.get("accountId"))) {
			para.put("accountId", bodyInfo.getString("accountId"));
		}
		if(bodyInfo.get("status") != null && !"".equals(bodyInfo.get("status"))) {
			para.put("status", bodyInfo.getString("status"));
		}
		
		if(bodyInfo.get("mallUuid") != null && !"".equals(bodyInfo.get("mallUuid"))) {
			para.put("mallUuid", bodyInfo.getString("mallUuid"));
		}
		
		if(manager.getType() == 3){
			para.put("productSellerId", manager.getProductSellerId());
		}
		
		Mall mall = mallService.selectByMallUuid(manager.getMallUuid()); 
		if(mall != null && !"商盟惠购".equals(mall.getMallName())){
			para.put("mallUuid", mall.getMallUuid());
		}
		
		List<Order> orderListAll = orderService.selectByPara(para);
		
		if(bodyInfo.get("page") != null && !"".equals(bodyInfo.get("page"))) {
			para.put("start", (Integer.valueOf(bodyInfo.getString("page"))-1)*Integer.valueOf(bodyInfo.getString("pageSize")));
		}
		if(bodyInfo.get("pageSize") != null && !"".equals(bodyInfo.get("pageSize"))) {
			para.put("size", Integer.valueOf(bodyInfo.getString("pageSize")));
		}
		
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		
		List<Order> orderList = orderService.selectByPara(para);
		
		if(orderList.size() <= 0){
			json.put("result", "1");
			json.put("description", "没有订单信息！");
			return buildReqJsonObject(json);
		}
		List<Map<String,String>> list = new ArrayList<>();
		for(Order order:orderList){
			Map<String,String> map = new HashMap<>();
			Mall orderMall = mallService.selectByMallUuid(order.getMallUuid());

			QqbsAccount account = qqbsAccountService.selectByAccountId(order.getAccountId());
			
			ProductSeller ps = productSellerService.selectByPrimaryKey(order.getSellerId());
			
			map.put("id", order.getId()+"");
			map.put("number", order.getNumber()+"");
			map.put("mallName", orderMall.getMallName()+"商城");
			map.put("sellerName", ps== null?"":ps.getName());
			map.put("accountId", order.getAccountId()+"");
			map.put("realPrice", order.getRealPrice()+"");
			if(account!=null){
				map.put("accountNickName", account.getNickname()==null?"":account.getNickname());				
			}else{
				map.put("accountNickName", "");
			}
			
			//订单状态；1：未付款，2：待发货，3：已发货，4：交易成功，5：用户取消（待退款团购），6：超时取消（已退款团购），7：团购进行中(团购)
			String status = "";
			switch(order.getStatus()){
			case 1:
				status = "未付款";
				break;
			case 2:
				status = "已支付,待发货";
				break;
			case 3:
				status = "已发货";
				break;
			case 4:
				status = "交易成功";
				break;
			case 5:
				status = "用户取消";
				break;
			}
			
			List<OrderProductRefund> oprList = orderProductRefundService.selectByOrderId(order.getId());
			if(oprList.size()>0){
				status = "退款订单";
			}
			
			map.put("status", status);
			
			//商品类别（0.非通信类;1.通信类）
			List<OrderProduct> opList	= orderProductService.selectByOrderId(order.getId());
			Map<String,Object> productPara = new HashMap<>();
			productPara.put("productId", opList.get(0).getProductId());
			List<Product> product = productService.selectByPara(productPara);
			String productType = "商品已下架";
			if(product.size()>0){
				switch(product.get(0).getType()){
				case 0:
					productType = "普通商品";
					break;
				case 1:
					productType = "套餐商品";
					break;
				}
			}
			
			map.put("productType", productType);
			
			map.put("remark", order.getRemark()==null?"":order.getRemark());
			map.put("createTime", order.getCreateTime()==null?"":sdf.format(order.getCreateTime()));
			map.put("payTime", order.getPayTime()==null?"":sdf.format(order.getPayTime()));
			map.put("sendTime", order.getSendTime()==null?"":sdf.format(order.getSendTime()));
			list.add(map);
		}
		
		session.setAttribute("ORDERLIST", list);
		
    	json.put("result", "0");
		json.put("description", "获取订单列表成功");
		json.put("list", list);
		json.put("count", orderListAll.size());

		return buildReqJsonObject(json);
	}
	
	@RequestMapping(value = "listOfProductType", method = RequestMethod.POST)
	@ResponseBody
	public String listOfProductType() {
		JSONObject json = new JSONObject();
		if (sign == 1) {
			json.put("result", "1");
			json.put("description", "请检查参数格式是否正确或者参数是否完整");
			return buildReqJsonInteger(1, json);
		}
		// 登录认证失败
		if (sign == 2) {
			json.put("result", "2");
			json.put("description", "账号未登录");
			return buildReqJsonInteger(2, json);
		}
		
		HttpSession session = request.getSession();
		Manager manager = (Manager) session.getAttribute("MANAGER");
        if(manager == null){
        	json.put("result", "1");
			json.put("description", "账号未登陆");
			return buildReqJsonObject(json);
        }
		
		JSONObject bodyInfo = JSONObject.fromObject(bodyString);
		
		Map<String,Object> para = new HashMap<>();
		if (bodyInfo.get("orderId") != null && !"".equals(bodyInfo.get("orderId"))) {
			para.put("orderId", bodyInfo.getString("orderId"));
		}
		if(bodyInfo.get("accountId") != null && !"".equals(bodyInfo.get("accountId"))) {
			para.put("accountId", bodyInfo.getString("accountId"));
		}
		if(bodyInfo.get("status") != null && !"".equals(bodyInfo.get("status"))) {
			para.put("status", bodyInfo.getString("status"));
		}
		if(bodyInfo.get("productType") != null && !"".equals(bodyInfo.get("productType"))) {
			para.put("productType", bodyInfo.getString("productType"));
		}
		Mall mall = mallService.selectByMallUuid(manager.getMallUuid()); 
		if(mall != null && !"商盟惠购".equals(mall.getMallName())){
			para.put("mallUuid", mall.getMallUuid());
		}
		
		List<Order> orderListAll = orderService.selectByPara(para);
		
		if(bodyInfo.get("page") != null && !"".equals(bodyInfo.get("page"))) {
			para.put("start", (Integer.valueOf(bodyInfo.getString("page"))-1)*Integer.valueOf(bodyInfo.getString("pageSize")));
		}
		if(bodyInfo.get("pageSize") != null && !"".equals(bodyInfo.get("pageSize"))) {
			para.put("size", Integer.valueOf(bodyInfo.getString("pageSize")));
		}
		
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		
		List<Order> orderList = orderService.selectByPara(para);
		
		if(orderList.size() <= 0){
			json.put("result", "1");
			json.put("description", "订单列表不存在");
			return buildReqJsonObject(json);
		}
		List<Map<String,String>> list = new ArrayList<>();
		for(Order order:orderList){
			Map<String,String> map = new HashMap<>();
			Mall orderMall = mallService.selectByMallUuid(order.getMallUuid());

			QqbsAccount account = qqbsAccountService.selectByAccountId(order.getAccountId());
			
			map.put("id", order.getId()+"");
			map.put("number", order.getNumber()+"");
			map.put("mallName", orderMall.getMallName()+"商城");
			map.put("accountId", order.getAccountId()+"");
			map.put("accountNickName", account.getNickname()+"");
			map.put("realPrice", order.getRealPrice()+"");
			
			//订单状态；1：未付款，2：待发货，3：已发货，4：交易成功，5：用户取消（待退款团购），6：超时取消（已退款团购），7：团购进行中(团购)
			String status = "";
			switch(order.getStatus()){
			case 1:
				status = "未付款";
				break;
			case 2:
				status = "待处理";
				break;
			case 3:
				status = "已处理";
				break;
			case 4:
				status = "历史订单";
				break;
			}
			map.put("status", status);
			
			//商品类别（0.非通信类;1.通信类）
			List<OrderProduct> opList	= orderProductService.selectByOrderId(order.getId());
			Map<String,Object> productPara = new HashMap<>();
			productPara.put("productId", opList.get(0).getProductId());
			List<Product> product = productService.selectByPara(productPara);
			String productType = "";
			switch(product.get(0).getType()){
			case 0:
				productType = "非通信类";
				break;
			case 1:
				productType = "通信类";
				break;
			}
			map.put("productType", productType);
			
			map.put("remark", order.getRemark()==null?"":order.getRemark());
			map.put("createTime", order.getCreateTime()==null?"":sdf.format(order.getCreateTime()));
			map.put("payTime", order.getPayTime()==null?"":sdf.format(order.getPayTime()));
			map.put("sendTime", order.getSendTime()==null?"":sdf.format(order.getSendTime()));
			list.add(map);
		}
		
		session.setAttribute("ORDERLIST", list);
		
    	json.put("result", "0");
		json.put("description", "获取订单列表成功");
		json.put("list", list);
		json.put("count", orderListAll.size());
		return buildReqJsonObject(json);
	}
	
	@RequestMapping(value = "detail", method = RequestMethod.POST)
	@ResponseBody
	public String detail() throws ParseException {
		JSONObject json = new JSONObject();
		if (sign == 1) {
			json.put("result", "1");
			json.put("description", "请检查参数格式是否正确或者参数是否完整");
			return buildReqJsonInteger(1, json);
		}
		// 登录认证失败
		if (sign == 2) {
			json.put("result", "2");
			json.put("description", "账号未登录");
			return buildReqJsonInteger(2, json);
		}
		
		HttpSession session = request.getSession();
		Manager manager = (Manager) session.getAttribute("MANAGER");
        if(manager == null){
        	json.put("result", "1");
			json.put("description", "账号未登陆");
			return buildReqJsonObject(json);
        }
		
		JSONObject bodyInfo = JSONObject.fromObject(bodyString);
		int right = 1;
		if(bodyInfo.get("orderId") == null || "".equals(bodyInfo.get("orderId"))) {
			right = 0;
		}
		if(right == 0){
			json.put("result", "1");
			json.put("description", "操作失败，请检查输入的参数是否完整");
			return buildReqJsonObject(json);
		}
		
		Order order = orderService.selectByPrimaryKey(Integer.valueOf(bodyInfo.getString("orderId")));
		
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		
		if(order == null){
			json.put("result", "1");
			json.put("description", "订单不存在");
			return buildReqJsonObject(json);
		}
		
		Map<String,Object> map = new HashMap<>();
		Mall orderMall = mallService.selectByMallUuid(order.getMallUuid());

		QqbsAccount account = qqbsAccountService.selectByAccountId(order.getAccountId());
		AccountPlatform ap = accountPlatformService.selectByAccountId(order.getAccountId());
		
		String fatherAccountId = "";
		String fatherAccountNickname = "";
		String shopAccountId = "";
		String shopAccountNickname = "";
		
		String currentfatherAccountId = "";
		String currentfatherAccountNickname = "";
		String currentshopAccountId = "";
		String currentshopAccountNickname = "";
		
		DateFormat  sdf2 = new SimpleDateFormat("yyyy-MM-dd");
		String strDate = "2017-08-20";
		Date date=sdf2.parse(strDate);
		System.out.println(date.toString());
		
		if(order.getCreateTime().before(date)){
			if(ap != null){
				if(ap.getFatherAccountId() != 0){
					QqbsAccount fatherAccount = qqbsAccountService.selectByAccountId(ap.getFatherAccountId());
					fatherAccountId = (fatherAccount==null?"":fatherAccount.getAccountId()+"");
					fatherAccountNickname = (fatherAccount==null?"":fatherAccount.getNickname());
				}
				
				if(ap.getShopAccountId() != 0){
					QqbsAccount shopAccount = qqbsAccountService.selectByAccountId(ap.getShopAccountId());
					shopAccountId = (shopAccount==null?"":shopAccount.getAccountId()+"");
					shopAccountNickname = (shopAccount==null?"":shopAccount.getNickname());
				}
			}
		}else{
			QqbsAccount fatherAccount = qqbsAccountService.selectByAccountId(order.getFatherAccountId());
			fatherAccountId = (fatherAccount==null?"":fatherAccount.getAccountId()+"");
			fatherAccountNickname = (fatherAccount==null?"":fatherAccount.getNickname());

			QqbsAccount shopAccount = qqbsAccountService.selectByAccountId(order.getShopAccountId());
			shopAccountId = (shopAccount==null?"":shopAccount.getAccountId()+"");
			shopAccountNickname = (shopAccount==null?"":shopAccount.getNickname());
		}
		
		if(ap != null){
			if(ap.getFatherAccountId() != 0){
				QqbsAccount fatherAccount = qqbsAccountService.selectByAccountId(ap.getFatherAccountId());
				currentfatherAccountId = (fatherAccount==null?"":fatherAccount.getAccountId()+"");
				currentfatherAccountNickname = (fatherAccount==null?"":fatherAccount.getNickname());
			}
			
			if(ap.getShopAccountId() != 0){
				QqbsAccount shopAccount = qqbsAccountService.selectByAccountId(ap.getShopAccountId());
				currentshopAccountId = (shopAccount==null?"":shopAccount.getAccountId()+"");
				currentshopAccountNickname = (shopAccount==null?"":shopAccount.getNickname());
			}
		}
		
		map.put("fatherAccountId", fatherAccountId);
		map.put("fatherAccountNickname", fatherAccountNickname);
		map.put("shopAccountId", shopAccountId);
		map.put("shopAccountNickname", shopAccountNickname);
		
		map.put("currentfatherAccountId", currentfatherAccountId);
		map.put("currentfatherAccountNickname", currentfatherAccountNickname);
		map.put("currentshopAccountId", currentshopAccountId);
		map.put("currentshopAccountNickname", currentshopAccountNickname);
		
		map.put("id", order.getId()+"");
		map.put("number", order.getNumber()+"");
		map.put("mallName", orderMall.getMallName()+"商城");
		map.put("accountId", order.getAccountId()+"");
		map.put("accountNickname", account==null?"":account.getNickname()+"");
		map.put("totalPrice", order.getTotalPrice()+"");
		map.put("realPrice", order.getRealPrice()+"");
		
		//订单状态；1：未付款，2：待发货，3：已发货，4：交易成功，5：用户取消（待退款团购），6：超时取消（已退款团购），7：团购进行中(团购)
		String status = "";
		switch(order.getStatus()){
		case 1:
			status = "未付款";
			break;
		case 2:
			status = "待处理";
			break;
		case 3:
			status = "已处理";
			break;
		case 4:
			status = "历史订单";
			break;
		}
		map.put("status", status);
		map.put("remark", order.getRemark()==null?"":order.getRemark());
		map.put("createTime", order.getCreateTime()==null?"":sdf.format(order.getCreateTime()));
		map.put("payTime", order.getPayTime()==null?"":sdf.format(order.getPayTime()));
		map.put("sendTime", order.getSendTime()==null?"":sdf.format(order.getSendTime()));
		map.put("receiveTime", order.getReceiveTime()==null?"":sdf.format(order.getReceiveTime()));
		
		//发货信息
		Map<String,Object> address = orderReceiveAddressService.getOrderAddressDetail(order.getReceiveAddressId());
		map.put("receiveAddress", address);
		
		//商品信息
		List<OrderProduct> orderProductList = orderProductService.selectByOrderId(order.getId());
		List<Map<String,Object>> productList = new ArrayList<>();
		for(OrderProduct op:orderProductList){
			DecimalFormat df=new DecimalFormat("0.00");
			Map<String,Object> productMap = new HashMap<>();
			Product product = productService.selectByPrimaryKey(op.getProductId());
			
			OrderProduct oprt=new OrderProduct();
			oprt.setOrderId(op.getOrderId());
			oprt.setProductId(op.getProductId());
			OrderProduct opt=orderProductService.selectByOrderIdAndProductId(oprt);
			
			String size = "",color = "",style = "", processingMethods = "";
			if(opt != null){
				ProductSize psize = productSizeService.selectByPrimaryKey(opt.getProductSizeId());
				ProductColor pc = productColorService.selectByPrimaryKey(opt.getProductColorId());
				ProductProcessingMethods ppm = productProcessingMethodsService.selectByPrimaryKey(opt.getProductProcessingMethodsId());
				ProductStyle pstyle = productStyleService.selectByPrimaryKey(opt.getProductStyleId());
				size = (psize==null?"":psize.getNameOfSize());
				color = (pc==null?"":pc.getNameOfColor());
				style = (pstyle==null?"":pstyle.getNameOfStyle());
				processingMethods = (ppm==null?"":ppm.getNameOfProcessingMethods());
			}
			
			productMap.put("size", size);
			productMap.put("color", color);
			productMap.put("style", style);
			productMap.put("processingMethods", processingMethods);
			
			productMap.put("productId", op.getProductId());
			productMap.put("name", product==null?"":product.getName());
			productMap.put("image", product==null?"":product.getImage1());
			productMap.put("count", op.getProductCount());
			productMap.put("salesPrice", op.getSalesPrice());
			productMap.put("totalPrice", df.format(op.getSalesPrice()*op.getProductCount()));
			productMap.put("certificateNumber", op.getCertificateNumber());
			
			//状态；1：申请中，2：待退货，3：待退款，4：退款成功，5：退款关闭，6：退款取消
			Map<String,Object> orderProductRefundMap = new HashMap<>();
			orderProductRefundMap.put("orderId", order.getId());
			orderProductRefundMap.put("orderProductId", op.getProductId());
			OrderProductRefund opr = orderProductRefundService.selectByOrderIdAndProductId(orderProductRefundMap);
			String productStatus = "无";
			if(opr != null){
				switch(opr.getStatus()){
				case 1:
					productStatus = "退款申请中";
					break;
				case 2:
					productStatus = "待退货";
					break;
				case 3:
					productStatus = "待退款";
					break;
				case 4:
					productStatus = "退款成功";
					break;
				case 5:
					productStatus = "退款关闭";
					break;
				case 6:
					productStatus = "退款取消";
					break;
				}
			}
			productMap.put("productStatus", productStatus);
			productList.add(productMap);
		}
		map.put("product", productList);
		
		//物流信息
		OrderLogistics ol = orderLogisticsService.selectByOrderId(order.getId());
		Map<String,Object> logisticsMap = new HashMap<>();
		if(ol != null){
			logisticsMap.put("channel", ol.getChannel()==null?"":ol.getChannel());
			logisticsMap.put("number", ol.getNumber()==null?"":ol.getNumber());
		}else{
			logisticsMap.put("channel", "暂无");
			logisticsMap.put("number", "暂无");
		}
		map.put("logistics", logisticsMap);
		
    	json.put("result", "0");
		json.put("description", "获取订单详情成功");
		json.put("order", map);
		return buildReqJsonObject(json);
	}
	
	
	/**
	 * 商家发货
	 * @return
	 */
	@RequestMapping(value = "sendOrder", method = RequestMethod.POST)
	@ResponseBody
	public String sendOrder() {
		JSONObject json = new JSONObject();
		if (sign == 1) {
			json.put("result", "1");
			json.put("description", "请检查参数格式是否正确或者参数是否完整");
			return buildReqJsonInteger(1, json);
		}
		// 登录认证失败
		if (sign == 2) {
			json.put("result", "2");
			json.put("description", "账号未登录");
			return buildReqJsonInteger(2, json);
		}
		
		HttpSession session = request.getSession();
		Manager manager = (Manager) session.getAttribute("MANAGER");
        if(manager == null){
        	json.put("result", "1");
			json.put("description", "账号未登陆");
			return buildReqJsonObject(json);
        }
		
		JSONObject bodyInfo = JSONObject.fromObject(bodyString);
		int right = 1;
		if(bodyInfo.get("orderId") == null || "".equals(bodyInfo.get("orderId"))) {
			right = 0;
		}else if(bodyInfo.get("logisticsCode") == null || "".equals(bodyInfo.get("logisticsCode"))){
			right = 0;
		}else if(bodyInfo.get("logisticsNumber") == null || "".equals(bodyInfo.get("logisticsNumber"))){
			right = 0;
		}
		if(right == 0){
			json.put("result", "1");
			json.put("description", "操作失败，请检查输入的参数是否完整");
			return buildReqJsonObject(json);
		}
		Order order = orderService.selectByPrimaryKey(Integer.valueOf(bodyInfo.getString("orderId")));
		if(order == null){
			json.put("result", "3");
			json.put("description", "操作失败，不存在该订单");
			return buildReqJsonObject(json);
		}
		order.setStatus(CommonConstant.ORDER_STATUS_3);
		order.setType(CommonConstant.ORDER_STATUS_3);
		Date date = new Date();
		order.setSendTime(date);
		
		Calendar calendar = new GregorianCalendar();
		calendar.setTime(date);
		calendar.add(Calendar.DATE,15);//把日期往后增加15天.整数往后推,负数往前移动 
		date = calendar.getTime();   //这个时间就是日期往后推15天的结果 
		order.setExpireTime(date);
		order.setUpdateTime(new Date());
		Integer rs = orderService.updateByPrimaryKeySelective(order);
        if(rs == 1){
        	json.put("result", "0");
			json.put("description", "订单发货成功");
			json.put("orderId", order.getId());
			
			OrderLogistics logistics = new OrderLogistics();
			logistics.setOrderId(order.getId());
			
			String companyName = KdCompanyEnum.getCompanyNameByKdnCode(bodyInfo.getString("logisticsCode"));
			logistics.setChannel(companyName);
			logistics.setNumber(bodyInfo.getString("logisticsNumber"));
			logistics.setCreateTime(new Date());
			
			Integer insertL = orderLogisticsService.insertSelective(logistics);
			if(insertL != 1){
				json.put("result", "1");
				json.put("description", "插入物流信息失败");
			}
			
        }else{
        	json.put("result", "1");
			json.put("description", "订单发货失败");
        }
		
		return buildReqJsonObject(json);
	}
	
	
	/**
	 * 商家发货
	 * @return
	 */
	@RequestMapping(value = "updateCertificateNumber", method = RequestMethod.POST)
	@ResponseBody
	public String updateCertificateNumber() {
		JSONObject json = new JSONObject();
		if (sign == 1) {
			json.put("result", "1");
			json.put("description", "请检查参数格式是否正确或者参数是否完整");
			return buildReqJsonInteger(1, json);
		}
		// 登录认证失败
		if (sign == 2) {
			json.put("result", "2");
			json.put("description", "账号未登录");
			return buildReqJsonInteger(2, json);
		}
		
		HttpSession session = request.getSession();
		Manager manager = (Manager) session.getAttribute("MANAGER");
        if(manager == null){
        	json.put("result", "1");
			json.put("description", "账号未登陆");
			return buildReqJsonObject(json);
        }
		
		JSONObject bodyInfo = JSONObject.fromObject(bodyString);
		int right = 1;
		if(bodyInfo.get("orderId") == null || "".equals(bodyInfo.get("orderId"))) {
			right = 0;
		}else if(bodyInfo.get("productId") == null || "".equals(bodyInfo.get("productId"))){
			right = 0;
		}else if(bodyInfo.get("certificateNumber") == null || "".equals(bodyInfo.get("certificateNumber"))){
			right = 0;
		}
		if(right == 0){
			json.put("result", "1");
			json.put("description", "操作失败，请检查输入的参数是否完整");
			return buildReqJsonObject(json);
		}
		Order order = orderService.selectByPrimaryKey(bodyInfo.getInt("orderId"));
		if(order == null){
			json.put("result", "3");
			json.put("description", "操作失败，不存在该订单");
			return buildReqJsonObject(json);
		}
		OrderProduct opt=new OrderProduct();
		opt.setOrderId(bodyInfo.getInt("orderId"));
		opt.setProductId(bodyInfo.getInt("productId"));
		opt.setCertificateNumber(bodyInfo.getString("certificateNumber"));
		int resuNumber=orderProductService.updateCertificateNumber(opt);

        if(resuNumber == 1){
        	json.put("result", "0");
			json.put("description", "保存成功");
			json.put("orderId", bodyInfo.getInt("orderId"));
        }else{
        	json.put("result", "1");
			json.put("description", "保存失败！");
        }
		
		return buildReqJsonObject(json);
	}
	
	@RequestMapping(value = "dealUplevel", method = RequestMethod.POST)
	@ResponseBody
    public String dealUplevel()
    {
		JSONObject json = new JSONObject();
		
		if (sign == 1) {
			json.put("result", "1");
			json.put("description", "请检查参数格式是否正确或者参数是否完整");
			return buildReqJsonInteger(1, json);
		}
		// 登录认证失败
		if (sign == 2) {
			json.put("result", "2");
			json.put("description", "账号未登录");
			return buildReqJsonInteger(2, json);
		}
		
		HttpSession session = request.getSession();
		Manager manager = (Manager) session.getAttribute("MANAGER");
        if(manager == null){
        	json.put("result", "1");
			json.put("description", "账号未登陆");
			return buildReqJsonObject(json);
        }
		
		JSONObject bodyInfo = JSONObject.fromObject(bodyString);
		int right = 1;
		if(bodyInfo.get("uplevelId") == null || "".equals(bodyInfo.get("uplevelId"))) {
			right = 0;
		}
		if(right == 0){
			json.put("result", "1");
			json.put("description", "操作失败，请检查输入的参数是否完整");
			return buildReqJsonObject(json);
		}
		
        try{
        	Map<String,Object> map = orderService.updateLog(Integer.valueOf(bodyInfo.get("uplevelId")+""),request);
        	String result = (String) map.get("result");
        	String description = (String) map.get("description");
        	if("1".equals(result)){
        		json.put("result", "1");
    			json.put("description", description);
        		return buildReqJsonObject(json);
        	}else{
        		json.put("result", 1);
        		json.put("description", "成功");
        		return buildReqJsonObject(json);
        	}
        }catch(Exception e){
        	json.put("result", "1");
			json.put("description", "操作失败");
			return buildReqJsonObject(json);
        }
    }
}
